package com.lagou.client;

import com.lagou.encoder.JSONSerializer;
import com.lagou.encoder.RpcEncoder;
import com.lagou.encoder.RpcRequest;
import com.lagou.service.UserService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Mrwg
 * @date 2020/5/23
 * @description
 */
public class RpcConsumer {
    private static ExecutorService executor =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    private static UserClientHander client;

    /**
     * 创建代理对象
     */
    public Object createProxy(final Class serviceClass, final String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                        new Class<?>[]{serviceClass}, (proxy, method, args) -> {
                            if (client == null) {
                                initClient();
                            }
                            RpcRequest request = new RpcRequest();
                            request.setRequestId(UUID.randomUUID().toString());
                            request.setClassName(serviceClass.getSimpleName());
                            request.setMethodName(method.getName());
                            request.setParameters(args);
                            request.setParameterTypes(new Class[]{String.class});
                            client.setPara(request);
                            return executor.submit(client).get();
                        });
    }

    /**
     * 初始化客户端
     */
    private static void initClient() throws InterruptedException {
        client = new UserClientHander();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 绑定出参格式为RpcRequest
                        pipeline.addLast(new RpcEncoder<>(RpcRequest.class, new JSONSerializer()));
                        // 绑定入参为String
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(client);
                    }
                });
        bootstrap.connect("127.0.0.1", 8990).sync();
    }


}
